package com.hoshiicloud.withdraw.controller.common;


import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hoshiicloud.common.controller.BaseController;
import com.hoshiicloud.common.rpc.Response;
import com.hoshiicloud.common.utils.DigestUtils;
import com.hoshiicloud.withdraw.entity.UrlInfo;
import com.hoshiicloud.withdraw.entity.UserContractPlatformRecord;
import com.hoshiicloud.withdraw.entity.UserInfo;
import com.hoshiicloud.withdraw.feign.SmsService;
import com.hoshiicloud.withdraw.param.Bank3RealCheckParam;
import com.hoshiicloud.withdraw.param.ContractPlatformParam;
import com.hoshiicloud.withdraw.param.SubscriptionInformatioParam;
import com.hoshiicloud.withdraw.service.UserBank3RealCheckService;
import com.hoshiicloud.withdraw.service.UserContractPlatformRecordService;
import com.hoshiicloud.withdraw.service.UserInfoService;
import com.hoshiicloud.withdraw.util.gongmao.AESEncryptUtil;
import com.hoshiicloud.withdraw.util.gongmao.ShortUrlUtil;
import com.hoshiicloud.withdraw.util.gongmao.SignUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.lang.reflect.Field;
import java.util.*;

/**
 * (UserInfo)表控制层
 *
 * @author makejava
 * @since 2019-08-21 17:31:42
 */
@RestController
@RequestMapping("/userInfo")
@Api(value = "提现用户信息", tags = {"提现用户信息"})
@Slf4j
public class UserInfoController extends BaseController {
	/**
	 * 服务对象
	 */
	@Autowired
	private UserInfoService userInfoService;

	/**
	 * 服务对象
	 */
	@Autowired
	private UserContractPlatformRecordService userContractPlatformRecordService;

	@Autowired
	private UserBank3RealCheckService bank3RealCheck;


	@Value("${gongmao.contractUrl}")
	private String contractUrl;

	@Value("${apiUrl}")
	private String apiUrl;

	/**
	 * 服务对象
	 */
	@Autowired
	private SmsService smsService;

	@ApiOperation(value = "查询提现用户是否签约过平台")
	@PostMapping("/subscriptionInformation")
	public Response subscriptionInformatio(@RequestBody @Valid SubscriptionInformatioParam param) {
		return Response.data(userInfoService.subscriptionInformation(param));
	}


	@ApiOperation(value = "查询提现用户签约记录")
	@PostMapping("/contractRecord")
	public Response contractRecord(@RequestBody @Valid SubscriptionInformatioParam param) {
		String s = userInfoService.contractRecord(param);
		if (s == null) {
			s = "0";
		}
		return Response.data(s);
	}

	/**
	 * 返回签约连接
	 *
	 * @param param
	 * @return
	 * @throws Exception
	 */
	@ApiOperation(value = "签约平台")
	@PostMapping("/contractPlatform")
	public Response contractPlatform(@RequestBody @Valid ContractPlatformParam param) throws Exception {

		// 判断用户三要素信息
		Bank3RealCheckParam bank3RealCheckParam = Bank3RealCheckParam.builder()
				.accountNo(param.getBankNum()).name(param.getName()).idCard(param.getIdNumber()).build();

		JSONObject jsonObject = bank3RealCheck.bank3RealCheck(bank3RealCheckParam);

		if (!"01".equals(jsonObject.getStr("status"))) {
			return Response.failed(jsonObject.getStr("msg"));
		}

		String appkey = SignUtil.getAPPKEY();
		String appsecret = SignUtil.getAPPSECRET();
		String aesKey = DigestUtils.md5(appkey + appsecret).toUpperCase();

		// 查询是否有过记录
		QueryWrapper<UserInfo> userInfoQueryWrapper = new QueryWrapper<>();
		userInfoQueryWrapper.lambda().eq(UserInfo::getName, param.getName())
				.eq(UserInfo::getIsDel, 0)
				.eq(UserInfo::getIdcard, param.getIdNumber());
		UserInfo userInfo = userInfoService.getOne(userInfoQueryWrapper);

		Integer userId = null;
		if (userInfo == null) {
			// 签约之前把用户添加入提现用户列表
			UserInfo build = UserInfo.builder().bankAccount(param.getBankNum()).name(param.getName()).mobile(param.getMobile())
					.idcard(param.getIdNumber()).createTime(new Date()).updateTime(new Date()).contractStatus("1").build();
			build.insert();
			userId = build.getId();
		} else {
			userId = userInfo.getId();
			UserInfo.builder().id(userId).updateTime(new Date()).contractStatus("1").build().updateById();
		}

		// 同时加入签约记录数据
		// 签约之前把用户添加入提现用户列表
		UserContractPlatformRecord userContractPlatformRecord = UserContractPlatformRecord.builder().idcard(param.getIdNumber()).bankAccount(param.getBankNum()).userId(userId).contractPlatformId(1)
				.bankAccount(param.getBankNum()).status("1").createTime(new Date()).updateTime(new Date()).build();
		userContractPlatformRecord.insert();

		// 将记录id
		param.setExtraParam(String.valueOf(userContractPlatformRecord.getId()));

		String longUrl = contractUrl + "&data=" + AESEncryptUtil.aesEncrypt(parseURLPair(param), aesKey);
		String shortUrl = ShortUrlUtil.ShortText(longUrl);


		// 插入地址映射关系
		UrlInfo.builder().longUrl(longUrl).shortUrl(shortUrl).contractPlatformRecordId(userContractPlatformRecord.getId()).createTime(new Date()).updateTime(new Date()).build().insert();

		String msg = "【好获严选】尊敬的好获家人，即日起，为更好的保障您的资金安全，" +
				"报酬提现需要签署协议，请点击以下链接完成协议签署，链接地址" + apiUrl + "/" + shortUrl +
				" 在线办理。如有疑问可咨询客服热线：4000238666";

		return smsService.sendSms(param.getMobile(), msg);
	}


	private static String parseURLPair(Object o) throws Exception {
		Class<?> c = o.getClass();
		Field[] fields = c.getDeclaredFields();
		Map<String, Object> map = new TreeMap<>();
		for (Field field : fields) {
			field.setAccessible(true);
			String name = field.getName();
			Object value = field.get(o);
			if (value != null)
				map.put(name, value);
		}
		Set<Map.Entry<String, Object>> set = map.entrySet();
		Iterator<Map.Entry<String, Object>> it = set.iterator();
		StringBuilder sb = new StringBuilder();
		while (it.hasNext()) {
			Map.Entry<String, Object> e = it.next();
			sb.append(e.getKey()).append("=").append(e.getValue()).append("&");
		}
		return sb.deleteCharAt(sb.length() - 1).toString();
	}

}